package com.aplink.generic.util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import java.io.File;
import java.util.Locale;

public class CameraUtils {
    public static final boolean ENABLE_SAVE_IMG_ON_INTERNAL_MEMORY = false;

    private static Uri getUriCaptureTemp( Context context ) {

        final String temporaryName = String.format( Locale.getDefault(), "%d.jpeg",
                System.currentTimeMillis() );

        final File file = getFile( context, temporaryName );
        if ( file != null ) {
            return Uri.fromFile( file );
        }

        return null;
    }

    public static File getFile( Context context, String filename ) {
        if ( ENABLE_SAVE_IMG_ON_INTERNAL_MEMORY ) {
            final String path = context.getFilesDir().getPath() + filename;
            final File file = new File( path );
            return file;
        } else {
            if ( android.os.Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED ) ) {
                return new File( Environment.getExternalStorageDirectory(),
                        filename );
            } else {
                return null;
            }
        }
    }

    public static Intent getIntentCropImage( Uri uri, Context context ) {
        final Intent intent = new Intent( "com.android.camera.action.CROP" );
        intent.setData( uri );
        intent.putExtra( "aspectX", 1 );
        intent.putExtra( "aspectY", 1 );
        intent.putExtra( "outputX", 320 );
        intent.putExtra( "outputY", 320 );
        final Uri tmpPath = CameraUtils.getUriCaptureTemp( context );
        intent.putExtra( MediaStore.EXTRA_OUTPUT, tmpPath );
        return intent;
    }

    /**
     * Utility for taking picture from Camera app.
     *
     * @return a valid Intent that we can start Camera app for taking photo.
     */
    public static Intent startCameraToTakePhoto( Context context ) {
        if ( context == null ) {
            return null;
        }
        Intent takePhotoIntent = null;
        takePhotoIntent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
        takePhotoIntent.putExtra( MediaStore.EXTRA_OUTPUT,
                getUriCaptureTemp( context ) );
        return takePhotoIntent;
    }
}
